using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace User.Api.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {

        private readonly IHostingEnvironment _env;
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(IHostingEnvironment env, ILogger<GlobalExceptionFilter> logger)
        {
            _env = env;
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (context.Exception.GetType() == typeof(UserOperationException))
            {

                var json = JsonErrorResponseMap(context.Exception.Message, context.Exception.StackTrace, context);
                context.Result = new BadRequestObjectResult(json);
            }
            else
            {
                var json = JsonErrorResponseMap("发生了未知内部错误", context.Exception.StackTrace, context);
                context.Result = new InternalServerErrorObjectResult(json);
            }
            _logger.LogError(context.Exception, context.Exception.Message);
            context.ExceptionHandled = true;
        }

        private JsonErrorResponse JsonErrorResponseMap(string message, string devloperMessage, ExceptionContext context)
        {
            var json = new JsonErrorResponse();
            json.Messsage = message;
            if (_env.IsDevelopment())
            {
                json.DevloperMessage = devloperMessage;
            }
            return json;
        }
    }
    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}